import 'dart:async'; //定时器需要
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../widget/mq_text.dart';
import '../../widget/mq_button.dart';
import '../../config/config.dart';
import '../../services/screen_adapter.dart';

class RegisterSecond extends StatefulWidget {

  final Map arguments;

  RegisterSecond({Key key, this.arguments}) : super(key: key);

  @override
  _RegisterSecondState createState() => _RegisterSecondState();
}

class _RegisterSecondState extends State<RegisterSecond> {

  String tel;
  bool sendCodeBtn = false;
  int seconds = 10;
  String code;

  @override
  void initState() {
    super.initState();
    tel = widget.arguments['tel'];
    _showTimer();
  }

  /// 倒计时
  _showTimer() {
    Timer.periodic(Duration(milliseconds: 1000), (timer){
      setState(() => seconds--);
      if (seconds == 0) {
      timer.cancel(); //清除定时器
      setState(() => sendCodeBtn = true);
    }
    });

  }

  /// 重新发送
  sendCode() async{
    setState(() {
      sendCodeBtn = false;
      seconds = 10;
      _showTimer();
    });

    var api = '${Config.domain}api/sendCode';
    var response = await Dio().post(api, data: {'tel': tel});
    if(response.data['success']) {
      print(response); // 服务器返回的验证码
    }
    
  }

  /// 验证码验证
  validateCode() async{
    var api = '${Config.domain}api/validateCode';
    var response = await Dio().post(api, data: {'tel': tel, 'code': code});
    if(response.data['success']) {
      print(response);
      Navigator.pushNamed(context, '/registerThird', arguments: {
        'tel': tel,
        'code': code
      });
    } else {
      Fluttertoast.showToast(
        msg: "${response.data['message']}",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.grey[600],
        textColor: Colors.white,
        fontSize: 16.0
      );
    }
    
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init();
    return Scaffold(
      appBar: AppBar(
        title: Text('用户注册-第二步')
      ),
      body: Container(
        padding: EdgeInsets.all(ScreenAdapter.width(20)),
        child: ListView(
          children: <Widget>[
            SizedBox(height: 50),
            Container(
              padding: EdgeInsets.only(left: 10),
              child: Text('短信已发送到您的手机$tel上, 请输入$tel手机号收到的验证码', style: TextStyle(
                color: Colors.black54
              ))
            ),
            SizedBox(height: 20),
            Stack(
              children: <Widget>[
                Container(
                  height: ScreenAdapter.height(80),
                  child: MqText(
                    text: '请输入验证码',
                    onChange: (value) {
                    code = value;
                    },
                  )
                ),
                Positioned(
                  right: 0,
                  top: 0,
                  child: sendCodeBtn? RaisedButton(
                    onPressed: sendCode,
                    child: Text('重新发送')
                  ):  RaisedButton(
                    onPressed: null,
                    child: Text('$seconds秒后重发')
                  )
                )
              ]
            ),
            SizedBox(height: 20),
            MqButton(
                text: '下一步',
                color: Colors.red,
                height: 74,
                callback: validateCode,
              )
          ]
        )
      )
    );
  }
}
